package tokenUtil

import (
	"commons/entity"
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
)

var PrivateKey = []byte("MIICXQIBAAKBgQDiIwn+A4DJAHLhw/SMcYUjtzAJkAOmzLJQKeeOdWR3LEi2Yze8iTZT5Izmivnz2n/S8doES3hOkEsl0ALA1Tf7m9a9nh0PPm/9lLIrHCOuTP6IRNs4iHe1Et0Vj7jVFIVRe5V6bN6VkgwdP627lScWr1P5Ir3f+kUWqHqrxsIuLQIDAQABAoGAFjtRoSpg/+HOaYmlQiVq7G73BwmkgkJ/iUgFXskFvn2ZDG1Grn9i2u6ON6AUILgrduaWA3QT+M1Qxf/kNWcA4MlLFFRqK/vd3u7SVlwpclKkcH0VINobxjyyR9OWlRtk4GxbJTXBzIVlg2U0d8sor3++THwaIOnW9tr65crZELUCQQDx5mGhAyg9FqPHnxPGXdch8FXvA4HolOv/ioLqESbJIhVaZaqogyWu7OB4UoWhJwr6JXbXBwxl7QONy1Lg+18DAkEA71FxL72qh7E1YMqSNaLvhWDL4f8NO7GpY7i+1d/qStT/crJFvQGW79/9nUjQfWDFAW/63p9iJJRw9LXA2WzfDwJBAIA79wlaGRy5Qb1zERKZcJBnTcbU/ysCt1DSZrAaw4rgbJ1tQ9jtHS7sF9rxNDHH9sPA1I0NCX+G89lZLehimW0CQDQxaeMElW10i3SpmUuTVnObUbvfGS68p3m1MAGLDRj27SNBmA4Ji7aS/kfQOpAti6mtl2P4FLpvmVb1ULLamKcCQQDgDCB+8W19tJe0XOBF2oHaURRm7MdVgCHZwzPaX5KqJ6IKvzr75Erl7AgjPxiRfzZZKW/o7NEMOefwcKYcUzZN")

var PublicKey = []byte(`MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgFYpJZ2TGbrXhZYmJrhUMoIlcJ/u
rgVayCnz2wY+txbKlelz+ahTjRGeR9J/95db2IU2bYGRl+0YlxsyoWw4B1ooR/XM
TP3D2fV9ynYVIqzwS8TenThlkxtxz2Y5GZ4z7/u5vR+m3HDztYQ7TCy8YlBw9W3p
wNydvbmvb9KjCXiRAgMBAAE=`)

/**
https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac
*/
type myCustomClaims struct {
	UserInfo entity.UserInfo
	jwt.StandardClaims
}

func Create(user entity.UserInfo) string {
	expires := int64(time.Now().Add(time.Duration(24*20) * time.Hour).Unix())

	claims := myCustomClaims{
		user,
		jwt.StandardClaims{
			ExpiresAt: expires,
			Issuer:    "test",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(PrivateKey)
	if err != nil {
		return ""
	}
	return ss
}
func Parse(accessToken string) (user entity.UserInfo, err error) {
	token, err := jwt.Parse(accessToken, func(token *jwt.Token) (interface{}, error) {
		return PrivateKey, nil
	})

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		userInfo := claims["UserInfo"].(map[string]interface{})

		if userInfo["Id"] != nil && userInfo["UserNickname"] != nil {
			if res, ok := userInfo["Id"].(float64); ok {
				user.Id = int64(res)
				user.UserNickname = userInfo["UserNickname"].(string)
				user.Avatar = userInfo["Avatar"].(string)
			}

		}
		//fmt.Println(reflect.TypeOf(users))
	} else if ve, ok := err.(*jwt.ValidationError); ok {
		if ve.Errors&jwt.ValidationErrorMalformed != 0 {
			err = errors.New("token 错误")
		} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
			// Token is either expired or not active yet
			err = errors.New("token 超时")
		}
	}
	return
}
